package jobs;


class MockDBConnection {
    public MockDBConnection() {
        // 模拟建立数据库连接
        System.out.println("数据库连接已建立");
    }

    public void query(String sql) {
        System.out.println("执行SQL: " + sql);
    }
}
public class DBConnectionSingleton {
    // 单例对象，volatile保证多线程下的可见性
    private static volatile DBConnectionSingleton instance = null;

    // 数据库连接对象
    private MockDBConnection connection = null;

    // 私有构造方法，防止外部实例化
    private DBConnectionSingleton() {}

    // 获取单例实例，双重检查锁定保证线程安全和性能
    public static DBConnectionSingleton getInstance() {
        if (instance == null) { // 第一次检查
            synchronized (DBConnectionSingleton.class) {
                if (instance == null) { // 第二次检查
                    instance = new DBConnectionSingleton();
                }
            }
        }
        return instance;
    }

    // 获取数据库连接对象，懒加载，线程安全
    public MockDBConnection getConnection() {
        if (connection == null) { // 第一次检查
            synchronized (this) {
                if (connection == null) { // 第二次检查
                    connection = new MockDBConnection();
                }
            }
        }
        return connection;
    }
}

 class Main {
    public static void main(String[] args) {
        // 多线程测试单例和连接的线程安全
        Runnable task = () -> {
            DBConnectionSingleton singleton = DBConnectionSingleton.getInstance();
            MockDBConnection conn = singleton.getConnection();
            conn.query("SELECT * FROM users");
        };

        Thread t1 = new Thread(task);
        Thread t2 = new Thread(task);
        t1.start();
        t2.start();
    }
}